package com.nari.ysphd.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.intel.webrtc.base.ActionCallback;
import com.intel.webrtc.base.WoogeenException;
import com.jeremyfeinstein.conference.YCHSConferenceClient;
import com.jeremyfeinstein.event.HDMsgEvent;
import com.jeremyfeinstein.exception.YchsException;
import com.jeremyfeinstein.gson.Meeting;
import com.jeremyfeinstein.gson.MeetingRoomBean;
import com.jeremyfeinstein.gson.OnResponse;
import com.jeremyfeinstein.listener.OnSocketListener;
import com.jeremyfeinstein.okhttputil.callback.StringCallback;
import com.jeremyfeinstein.utils.AppConstants;
import com.jeremyfeinstein.utils.ConferenceApp;
import com.jeremyfeinstein.utils.ConfigUtil;
import com.jeremyfeinstein.utils.NetUtils.ApiResponse;
import com.jeremyfeinstein.utils.NetUtils.JsonCallback;
import com.jeremyfeinstein.utils.NetUtils.SGApiService;
import com.jeremyfeinstein.utils.SPUtil;
import com.jeremyfeinstein.utils.SwitchToMainThread;
import com.jeremyfeinstein.utils.ToastUtil;
import com.jeremyfeinstein.utils.YCHSWebSocketAPI;
import com.jeremyfeinstein.utils.YCHShttpAPI;
import com.nari.ysphd.MyApp;
import com.nari.ysphd.R;
import com.nari.ysphd.adapter.OngoingMeetingsAdapter;
import com.nari.ysphd.base.AbsAdapter;
import com.nari.ysphd.base.BaseMeetingFragment;
import com.nari.ysphd.listener.OnGoingMeetingListener;
import com.nari.ysphd.ui.ConferenceRoomUI;
import com.nari.ysphd.ui.IPConfigActivity;
import com.nari.ysphd.ui.TimeOutActivity;
import com.nari.ysphd.util.ActivityManager;
import com.nari.ysphd.util.log.HDMsgUtils;
import com.nari.ysphd.util.log.MLog;
import com.nari.ysphd.view.JoinMeetDialog;
import com.orhanobut.logger.Logger;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import nari.mip.core.Platform;
import okhttp3.Call;

import static com.nari.ysphd.util.log.HDMsgUtils.getDevCode;
import static com.nari.ysphd.util.log.HDMsgUtils.getTotalBytes;

/**
 * Create by sunxunchao on 2019/3/29
 * 正在进行的互动
 */
public class OngoingMeetingsFragment extends BaseMeetingFragment {

    private static final String TAG = "OngoingMeetingsFragment";

    private OngoingMeetingsAdapter adapter;
    private JoinMeetDialog joinMeetDialog;
    private ProgressDialog progressDialog;
    private String multiFlag = "0"; //二级互动flag 判定，0 为本地进入 1 为网省访问

    private HandlerThread handlerThread = new HandlerThread("j_io");

    private Handler handler;

    private static final String MEETING_O_FWORD = "meetingOfWord";
    private static final int STIO = 8000;

    public static Fragment newInstance(String meetingOfWord) {
        Bundle bundle = new Bundle();
        bundle.putString(MEETING_O_FWORD, meetingOfWord);
        OngoingMeetingsFragment f = new OngoingMeetingsFragment();
        f.setArguments(bundle);
        return f;
    }

    @Override
    protected void initViews(View rootView) {
        super.initViews(rootView);
        adapter.setOnGoingMeetingListener(listener);
        handlerThread.start();
//        handler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
//            @Override
//            public boolean handleMessage(Message msg) {
//                switch (msg.what){
//                    case STIO:
//                        MeetingRoomBean meetingRoomBean = new Gson().fromJson((String) msg.obj, MeetingRoomBean.class);
//                        connectToMeetingRoom(meetingRoomBean);
//                        break;
//                }
//                return false;
//            }
//        });

        handler = new Handler(handlerThread.getLooper());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        HDMsgUtils.getInstance().init();
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    long startTimeMillis = 0;
    long startBytes = 0;

    public void onEventMainThread(HDMsgEvent event) {
        MLog.e(TAG, "hdmsg: event.url " + event.url);
        MLog.e(TAG, "hdmsg: event.MsgType " + event.MsgType);
        String devCode = getDevCode();
        if (event.MsgType == HDMsgEvent.Type.start) {
            startTimeMillis = System.currentTimeMillis();
            startBytes = getTotalBytes();
            String serverIp = (String) SPUtil.get(AppConstants.YCHS_IP, "");

            MLog.e(TAG, "onEventMainThread:----------------------------------= ");
            MLog.e(TAG, "onEventMainThread:serverIp = " + serverIp);
            MLog.e(TAG, "onEventMainThread:----------------------------------= ");
            SGApiService.postJSON("deviceRunStart")
                    .addParam("devCode", devCode)
                    .addParam("serverIp", serverIp)
                    .post(getCallback());

        } else if (event.MsgType == HDMsgEvent.Type.stop && startTimeMillis > 0) {

            long timeMillis = System.currentTimeMillis() - startTimeMillis;
            long timeS = timeMillis / 1000;
            long timeM = timeS / 60;

            String duration = timeM + "." + timeS % 60;

            long endBytes = getTotalBytes() - startBytes;
            DecimalFormat format = new DecimalFormat("0.00");
            double i = (endBytes / (1024.0 * 1024.0));
            String consumeFlow = format.format(i);

            MLog.e(TAG, "onEventMainThread:----------------------------------= ");
            MLog.e(TAG, "onEventMainThread: HDMsgUtils url = " + HDMsgUtils.baseUrl);
            MLog.e(TAG, "onEventMainThread:----------------------------------= ");

            SGApiService.postJSON("deviceRunOver")
                    .addParam("devCode", devCode)
                    .addParam("duration", duration)
                    .addParam("consumeFlow", consumeFlow)
                    .post(getCallback());

            startTimeMillis = 0;
            startBytes = 0;
        }
    }

    private JsonCallback<String> getCallback() {
        return new JsonCallback<String>() {
            @Override
            public void onSuccess(ApiResponse<String> response) {
                super.onSuccess(response);
                Logger.e("Response  %s", "onSuccess: " + response.body);
            }

            @Override
            public void onError(ApiResponse<String> response) {
                super.onError(response);
                Logger.e("Response  %s", "onError: " + response.message);
            }
        };
    }

    @Override
    protected AbsAdapter getAdapter() {
        adapter = new OngoingMeetingsAdapter(getActivity(), R.layout.adapter_ongoing_meetings);
        return adapter;
    }

    @Override
    protected String getMeetingListType() {
        return "2,3";
    }

    @Override
    protected String getMeetingOfWords() {
        return getArguments().getString(MEETING_O_FWORD);
    }

    private OnGoingMeetingListener listener = new OnGoingMeetingListener() {

        @Override
        public void onJoinClicked(View view, Meeting meeting) {
            joinMeetDialog = new JoinMeetDialog(getActivity(), new OnJoinClick(meeting));
            if ("2".equals(meeting.getDataSource()) && ConfigUtil.getInstance().getMeeting_resource().equals("1")) {
                ConfigUtil.getInstance().setTurnPort(ConfigUtil.getInstance().getMCUPort3());
                ConfigUtil.getInstance().setMCUPort(ConfigUtil.getInstance().getAgentServer());
                AppConstants.turnAddrTCP = "turn:" + ConfigUtil.getInstance().getAgentServer() + ":" + ConfigUtil.getInstance().getTurnPort() + "?transport=tcp";
            } else {
                ConfigUtil.getInstance().setMCUPort(ConfigUtil.getInstance().getLocalPort4());
                ConfigUtil.getInstance().setTurnPort(ConfigUtil.getInstance().getLocalPort3());
                AppConstants.turnAddrTCP = "turn:" + ConfigUtil.getInstance().getRemoteUrl() + ":" + ConfigUtil.getInstance().getTurnPort() + "?transport=tcp";
            }

            if ("1".equals(meeting.getJoinStatus())) { //被邀请人直接加入会议，无需输入密码
                if (progressDialog == null)
                    progressDialog = ProgressDialog.show(getActivity(), null, "正在处理...");
                else
                    progressDialog.show();
                forceLeave(meeting, meeting.getInvite_code());
            } else {
                joinMeetDialog.showAtLocation(view, Gravity.CENTER, 0, 0);
            }
        }

        @Override
        public void onPauseClicked(View view, View view1, Meeting meeting) {
            pauseMeeting((Button) view, (Button) view1, String.valueOf(view.getTag()), meeting);

        }
    };


    private void pauseMeeting(final Button btn_pause, final Button btn_join, String pauseFlag1, final Meeting meeting) {
        Map<String, String> params = new HashMap<>();
        params.put("flag", pauseFlag1);
        params.put("meetingId", meeting.getMeetingId());
        YCHShttpAPI.PauseMeeting(getActivity(), params, new StringCallback() {
            @Override
            public void onError(Call call, int statusCode, Exception e) {
                if ((Integer) btn_pause.getTag() == 1) {
                    Toast.makeText(getActivity(), "互动取消暂停失败！", Toast.LENGTH_SHORT).show();
                } else if ((Integer) btn_pause.getTag() == 0) {
                    Toast.makeText(getActivity(), "互动暂停失败！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onResponse(String response) {
                OnResponse resp = YCHShttpAPI.getOnResponse(response);
                meeting.setStatus(resp.getStatus());
                if ("0".equals(resp.getResultCode())) {
                    if ("4".equals(resp.getStatus())) {// 4 暂停的互动
                        Toast.makeText(getActivity(), "互动已暂停!", Toast.LENGTH_SHORT).show();
                        btn_pause.setText("取消暂停");
                        btn_join.setVisibility(View.GONE);
                        btn_pause.setTag(1);
                    } else if ("2".equals(resp.getStatus())) {
                        btn_pause.setText("暂停互动");
                        btn_join.setVisibility(View.VISIBLE);
                        btn_pause.setTag(0);
                        Toast.makeText(getActivity(), "互动已取消暂停！", Toast.LENGTH_SHORT).show();
                    }
                } else if ("-2".equals(resp.getResultCode())) {
                    Intent intent = new Intent(getActivity(), TimeOutActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), String.valueOf(resp.getErrorMessage()), Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void forceLeave(final Meeting meeting, final String invite_code) {
        YCHSConferenceClient.getInstance().leave(new ActionCallback<Void>() {
            @Override
            public void onFailure(WoogeenException arg0) {
                joinMeeting(meeting, invite_code);

            }

            @Override
            public void onSuccess(Void arg0) {

                joinMeeting(meeting, invite_code);
            }
        });
    }

    private class OnJoinClick implements View.OnClickListener {

        private Meeting meeting;

        public OnJoinClick(Meeting meeting) {
            this.meeting = meeting;
        }

        @Override
        public void onClick(View v) {
            final String invite_code = joinMeetDialog.getInvite_code_input().getText().toString();

            if (TextUtils.isEmpty(invite_code)) {
                Toast.makeText(getActivity(), "请输入密码", Toast.LENGTH_SHORT).show();
                joinMeetDialog.getInvite_code_input().requestFocus();
                return;
            }
            if (joinMeetDialog != null && joinMeetDialog.isShowing()) {
                joinMeetDialog.dismiss();
            }
            progressDialog = ProgressDialog.show(getActivity(), null, "正在处理...");
            joinMeeting(meeting, invite_code);

            //joinMeeting(meeting,ConfigUtil.getApp().encryptLoginPwd(invite_code));
        }
    }


    /**
     * 加入互动
     *
     * @param invite_code
     */
    private void joinMeeting(final Meeting meeting, final String invite_code) {
        YCHShttpAPI.remoteSignIn(getActivity(), meeting.getMeetingId(), new StringCallback() {

            @Override
            public void onError(Call call, int statusCode, Exception e) {
                ToastUtil.showToast("加入互动失败，无法连接服务器");
                Log.e(TAG, "joinMeeting " + e.getMessage());
                dismissDialog();
            }

            @Override
            public void onResponse(String response) {
                OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                String url = "";
                if ("0".equals(onResponse.getResultCode())) {
                    if ("false".equals(onResponse.getFlag())) {
                        Logger.e("一级互动: " + (AppConstants.REQUEST_MODE + ConfigUtil.getInstance().getRemoteUrl() + ":" + ConfigUtil.getInstance().getRemotePort()));
                        url = AppConstants.REQUEST_MODE + ConfigUtil.getInstance().getRemoteUrl() + ":" + ConfigUtil.getInstance().getRemotePort();
                        AppConstants.isLocalMeeting = true;
                        multiFlag = "0";
                    } else {
                        String port = AppConstants.isHttps ? (String) SPUtil.get(AppConstants.SERVER_PORT5, "") : (String) SPUtil.get(AppConstants.SERVER_PORT1, "");
                        Logger.e("二级互动:  " + port);
                        url = AppConstants.REQUEST_MODE + ConfigUtil.getInstance().getAgentServer() + ":" + port;
                        // AppConstants.SERVER_URL = AppConstants.HTTP + ConfigUtil.getApp().getRemoteUrl()+":"+ConfigUtil.getApp().getAppServerHttpPort();
                        multiFlag = "1";
                        if ("1".equals(AppConstants.meetingResoure)) {
                            AppConstants.isLocalMeeting = false;
                        }
                    }
                    SPUtil.put(AppConstants.MCU_ADDRESS, url);
                    checkJoinMeeting(url, meeting, invite_code);
                } else if ("-2".equals(onResponse.getResultCode())) {
                    Intent intent = new Intent(getActivity(), TimeOutActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {
//                    if (AppConstants.TAG_LOGINOUT.equals(onResponse.getErrorMessage())){
//                        ActivityManager.getInstance().finishActivityExcept(IPConfigActivity.class);
//                        Platform.getCurrent().stop(MyApp.getApp());
//                        ToastUtil.showLong(MyApp.getApp(),onResponse.getErrorMessage());
//                        return;
//                    }
                    ToastUtil.showToast("加入互动： " + onResponse.getErrorMessage());
                    dismissDialog();
                }
            }
        });
    }


    private void checkJoinMeeting(String url, final Meeting meeting, String invite_code) {
//        String url = "";
//        if (AppConstants.isLocalMeeting) {
//            url = ConfigUtil.getApp().getLocalSocketUrl();
//        } else {
//            url = ConfigUtil.getApp().getRemoteSocketUrl();
//        }
        Log.d(TAG, "checkJoinMeeting start... ");
        YCHShttpAPI.CheckJoinMeeting(getActivity(), url, invite_code, meeting.getMeetingId(), multiFlag, new StringCallback() {
            @Override
            public void onResponse(String response) {
                dismissDialog();
                OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                if ("0".equals(onResponse.getResultCode())) {
                    Logger.e("视频编码格式 :" + onResponse.getCompressType());
                    ConfigUtil.getInstance().setCompressType(onResponse.getCompressType()); //存储编码视频格式
                    ConfigUtil.getInstance().setLocalPort(onResponse.getLocal_port3(), onResponse.getLocal_port4());
                    Logger.e("port3 =" + onResponse.getLocal_port3() + " port4 =" + onResponse.getLocal_port4());
                    ConfigUtil.getInstance().setMcuServerIP(onResponse.getMcuServerIp());
                    //  AppConstants.turnAddrTCP = "turn:" + ConfigUtil.getApp().getMcuServerIP() + ":" + ConfigUtil.getApp().getLocalPort3() + "?transport=tcp";
                    AppConstants.turnAddrTCP = "turn:" + ConfigUtil.getInstance().getAgentServer() + ":" + ConfigUtil.getInstance().getLocalPort3() + "?transport=tcp";
                    Logger.e("turnAddrTCP :" + AppConstants.turnAddrTCP);

                    final MeetingRoomBean meetingRoomBean = new MeetingRoomBean();
                    meetingRoomBean.setMcuRoomId(onResponse.getMcu_room_id());
                    meetingRoomBean.setMeetingId(meeting.getMeetingId());
                    meetingRoomBean.setMeetingName(meeting.getMeetingName());
                    meetingRoomBean.setStartTime(meeting.getStartTime());
                    meetingRoomBean.setRole(onResponse.getRole());
                    String meetingRoomBeanStr = new Gson().toJson(meetingRoomBean);
//                    if (handler != null){
//                        handler.handleMessage(handler.obtainMessage(STIO, meetingRoomBeanStr));
//                    }

                    if (handler != null) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                connectToMeetingRoom(meetingRoomBean);
                            }
                        });
                    }
                } else if ("-2".equals(onResponse.getResultCode())) {
                    Intent intent = new Intent(getActivity(), TimeOutActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {
//                    if (AppConstants.TAG_LOGINOUT.equals(onResponse.getErrorMessage())){
//                        ActivityManager.getInstance().finishActivityExcept(IPConfigActivity.class);
//                        Platform.getCurrent().stop(MyApp.getApp());
//                        ToastUtil.showLong(MyApp.getApp(),onResponse.getErrorMessage());
//                        return;
//                    }
                    ToastUtil.showToast(onResponse.getErrorMessage());
                    Log.e(TAG, "chekcJoinMeeting ：" + onResponse.getErrorMessage());
                }
            }

            @Override
            public void onError(Call call, int statusCode, Exception e) {
                ToastUtil.showToast("加入互动失败");
                dismissDialog();
            }
        });
    }

    private void connectToMeetingRoom(final MeetingRoomBean meetingRoomBean) {
        Log.d(TAG, "connectToMeetingRoom: start");
        //  final CountDownLatch latch = new CountDownLatch(2);

        if (!YCHSWebSocketAPI.getInstance().isSocketConnected()) {
            String localUrl = ConfigUtil.getInstance().getLocalSocketUrl();
            YCHSWebSocketAPI.getInstance().initSocket(localUrl);
            YCHSWebSocketAPI.getInstance().setOnSocketListener(new OnSocketListener() {
                @Override
                public void onError(int code, final YchsException e) {
                    SwitchToMainThread.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            dismissDialog();
                            Log.e(TAG, "onError socket : " + e.getMessage());
                        }
                    });
                }

                @Override
                public void onConnectSuccess() {
                    //latch.countDown();
                }
            });
        } else {
            //  latch.countDown();
        }

        if ((Boolean) SPUtil.get(AppConstants.HAS_REMOTE_SOCKET, false) &&
                !YCHSWebSocketAPI.getInstance().isRemoteSocketConnected()) {
            String remoteUrl = (String) SPUtil.get(AppConstants.REMOTE_SOCKET_URL, "");
            YCHSWebSocketAPI.getInstance().initRemoteSocket(remoteUrl);
            YCHSWebSocketAPI.getInstance().setOnRemoteSocketListener(new OnSocketListener() {
                @Override
                public void onError(int code, final YchsException e) {
                    SwitchToMainThread.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            dismissDialog();
                            Log.e(TAG, "onError remote socket : " + e.getMessage());
                        }
                    });
                }

                @Override
                public void onConnectSuccess() {
                    // latch.countDown();
                }
            });
        } else {
            //latch.countDown();
        }

        try {
            //latch.await();
            SwitchToMainThread.getInstance().post(new Runnable() {
                @Override
                public void run() {
                    dismissDialog();
                    Intent intent = new Intent(getActivity(), ConferenceRoomUI.class);
                    intent.putExtra(ConferenceRoomUI.MCU_ROOMID, meetingRoomBean.getMcuRoomId());
                    intent.putExtra(ConferenceRoomUI.MEETING_ID, meetingRoomBean.getMeetingId());
                    intent.putExtra(ConferenceRoomUI.MEETING_NAME, meetingRoomBean.getMeetingName());
                    intent.putExtra(ConferenceRoomUI.MEETING_SART_TIME, meetingRoomBean.getStartTime());
                    intent.putExtra(ConferenceRoomUI.MCU_ROLE, meetingRoomBean.getRole());
                    intent.putExtra("joinFlag", "1");
                    startActivity(intent);
                }
            });
        } catch (Exception e) {
            SwitchToMainThread.getInstance().post(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.showLong(ConferenceApp.getApp(), "加入会议错误");
                }
            });
        }
    }

    private void dismissDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }


    @Override
    public void onDestroy() {
        if (handler != null) {
            handler.removeMessages(STIO);
        }
        super.onDestroy();
    }


}
